package com.kun.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.Channel;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author FangKun
 * @create 2024-02-03-13:27
 */
public class SelectorThreadGroup {

    SelectorThread[] sts;
    ServerSocketChannel server;
    AtomicInteger xid = new AtomicInteger(3);

    SelectorThreadGroup(int num){
        sts = new SelectorThread[num];

        for (int i = 0; i < num; i++) {
            sts[i] = new SelectorThread(this);

            new Thread(sts[i]).start();
        }
    }

    public void bind(int port) {

        try {
            server = ServerSocketChannel.open();
            server.configureBlocking(false);
            server.bind(new InetSocketAddress(port));

            //注册到哪个selector？
            nextSelector(server);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void nextSelector(Channel c) {

        SelectorThread st = next();

        //通过队列传递数据
        st.lbq.add(c);
        //通过打断阻塞，让对应的线程自己在打断后注册 selector
        st.selector.wakeup();

        //ServerSocketChannel s = (ServerSocketChannel)c;
        /*try {
            s.register(st.selector, SelectionKey.OP_ACCEPT);
            st.selector.wakeup();

        } catch (ClosedChannelException e) {
            e.printStackTrace();
        }*/

    }

    private SelectorThread next() {
        int index = xid.incrementAndGet() % sts.length;
        return sts[index];
    }
}
